<template>
	<view class="page" :style="{height:pageHeight+'px', background:`rgba(${mainColor[0]}, ${mainColor[1]}, ${mainColor[2]}, 0.5)`}">
		<view class="kui-flex kui-flex-center" v-if="data">
			<view style="filter: blur(250rpx);-webkit-filter: blur(200rpx);position: relative;left: 200rpx;"><canvas canvas-id="myCanvas0" :style="{height:pageHeight+'px'}"></canvas></view>
			<view style="position: absolute;width: 750rpx;" :style="{height:pageHeight+'px'}">
				<!-- 刘海屏占位 -->
				<view :style="{paddingTop:(sysInfo ? sysInfo.safeArea.top+10 : 60) + 'rpx'}"></view>
				<view class="kui-header kui-flex kui-flex-space-between kui-flex-vcenter kui-padding">
					<view class="kui-relative" style="top: 5rpx;" @tap="back"><uni-icons type="arrowdown" size="20" color="rgba(255, 255, 255, 0.7)"></uni-icons></view>
					<view class="kui-flex">
						<block v-for="(item, index) in switchList" :key="index">
							<view class="kui-padding kui-flex kui-flex-vcenter" style="height: 30rpx;" :class="index == 0 ? 'kui-border-r-color-opacity5' : ''" @tap="switchTaped(item)">
								<text class="kui-color-white kui-text-small1" :class="!item.active ? 'kui-opacity3' : ''">{{ item.title }}</text>
							</view>
						</block>
					</view>
					<view><uni-icons type="redo" size="20" color="rgba(255, 255, 255, 0.7)"></uni-icons></view>
				</view>
				<!-- 歌曲界面 -->
				<block v-if="switchId == 0">
					<view class="kui-padding-top kui-flex kui-flex-center kui-padding">
						<image class="kui-border-radius-small song-pic" :src="data.al.picUrl" v-if="data"></image>
					</view>
					<view class="kui-margin-top kui-padding">
						<view class="kui-flex kui-flex-space-between kui-flex-vcenter kui-padding-small">
							<view><uni-title :title="data.name" type="h1" color="#FFFFFF"></uni-title></view>
							<view><uni-icons type="heart" color="rgba(255, 255, 255, 0.7)" size="28"></uni-icons></view>
						</view>
						<view class="kui-padding-small">
							<text class="kui-text-small1 kui-color-white-opacity8">{{ handleSongArtlist(data.ar) }}</text>
						</view>
						<view class=" kui-padding-vcenter kui-flex kui-flex-center kui-flex1" style="position: fixed; bottom: 0;width: 680rpx;margin-bottom: 60rpx;">
							<view>
								<view class="kui-padding-vcenter">
									<movable-area class="kui-margin-top kui-flex slider-active kui-bg-white-opacity3 slider-area kui-border-radius" id="slider-area" style="width: 630rpx;">
										<view class="kui-bg-white slider-active" :style="{width:sliderMoveX+'px'}"></view>
										<movable-view :x="sliderMoveX" direction="horizontal" class="slider-point kui-bg-green" style="width: 3px;height: 3px;" @change="changeBySlider"></movable-view>
									</movable-area>
									<view class="kui-flex kui-flex-space-between" style="margin-top: 8rpx;" v-if="songUrlData">
										<text class="kui-color-white-opacity8 kui-text-small">{{ songCurrentTime }}</text>
										<text class="kui-color-white-opacity8 kui-text-small" v-if="songUrlData.url">{{ songEndTime }}</text>
										<text class="kui-color-white-opacity8 kui-text-small" v-else>00:00</text>
									</view>
								</view>
								<view class="kui-flex kui-margin-top">
									<block v-for="(item, index) in bottomBarList" :key='index'>
										<view class=" kui-flex kui-flex1 kui-flex-column kui-flex-center">
											<view class="kui-flex kui-flex-vcenter kui-flex-center" :class="[(index < 2 ? 'kui-flex-start' : ''), (index > 2 ? 'kui-flex-end' : '')]">
												<rich-text class="iconfont kui-relative kui-color-white kui-relative" :class="(index == 0 || index == 4) ? 'kui-color-white-opacity8' : ''" :nodes="item.iconcode" :style="{fontSize:item.size+'rpx', top:index == 4 ? '5rpx' : '0rpx'}" @tap="tapedBottomBar(index)"></rich-text>
											</view>
										</view>
									</block>
								</view>
							</view>
						</view>
					</view>
				</block>
				<!-- 歌词界面 -->
				<block v-else>
					<view class="kui-padding">
						<view class="kui-padding-small">
							<view class="kui-flex kui-flex-space-between kui-flex-vcenter">
								<view><uni-title :title="data.name" type="h1" color="#FFFFFF"></uni-title></view>
								<!-- <view><uni-icons type="heart" color="rgba(255, 255, 255, 0.7)" size="28"></uni-icons></view> -->
							</view>
							<view>
								<text class="kui-text-small1 kui-color-white-opacity8">{{ handleSongArtlist(data.ar) }}</text>
							</view>
							<view style="height: 90rpx;"></view>
							<scroll-view class="kui-flex kui-flex-column kui-flex-center kui-flex-vcenter" :scroll-top="scrollTopByLyric" :scroll-with-animation="true" :scroll-y="true" :style="{height:(pageHeight-250)+'px'}">
								<block v-for="(item, index) in songLyric" :key="index" v-if="songLyric.length > 0">
									<view v-if="index == 0" style="position: fixed;width: 660rpx;overflow: hidden;z-index: 99999;" :style="{height:songLyricLineHeight+'rpx'}"></view>
									<view v-if="index == 0" :style="{height:songLyricLineHeight+'rpx'}"></view>
									<view class="kui-text kui-color-white-opacity5" :class="item.active ? 'kui-text-s32 kui-text-scale-transition kui-text-bold' : ''" :style="{height:songLyricLineHeight+'rpx', color:item.active ? `rgba(${mainColor[0]}, ${mainColor[1]}, ${mainColor[2]}, .5)` : ''}"><text>{{ item.lyric }}</text></view>
								</block>
								<block v-if="songLyric.length == 0">
									<view class="kui-flex kui-flex-vcenter kui-flex-center kui-text kui-color-white-opacity5" :style="{height: songLyricLineHeight+'rpx'}">
										<text class="kui-text">歌词获取中...</text>
									</view>
								</block>
							</scroll-view>
						</view>
						<!-- 播放暂停按钮 -->
						<view class="kui-padding-top kui-flex kui-flex-end">
							<rich-text class="iconfont kui-color-white" :style="{fontSize:(bottomBarList[2].size-30)+'rpx'}" :nodes="bottomBarList[2].iconcode" @tap="tapedBottomBar(2)"></rich-text>
						</view>
					</view>
				</block>
			</view>
		</view>
	</view>
</template>

<script>
	let innerAudioContext;
	export default {
		data() {
			return {
				id: 0,
				data: null,
				pageHeight: 0,
				mainColor: 'rgba(255, 255, 255, 1)',
				switchList: [{
					id: 0,
					title: '歌曲',
					active: true
				}, {
					id: 1,
					title: '歌词',
					active: false
				}],
				bottomBarList: [{
					title: '循环播放',
					iconcode: '&#xea75;',
					size: 40
				}, {
					title: '上一曲',
					iconcode: '&#xe616;',
					size: 50
				}, {
					title: '播放',
					iconcode: '&#xea82;',
					size: 100
				}, {
					title: '下一曲',
					iconcode: '&#xe615;',
					size: 50
				}, {
					title: '播放列表',
					iconcode: '&#xea86;',
					size: 36
				}],
				switchId: 0,
				songUrlData: null,
				songCurrentTime: '00:00',
				songEndTime: '00:00',
				playStatus: false,
				currentPercent: 0.1,
				sliderMoveX: 0 ,// 滑块移动距离
				sliderMaxWidth: 0 ,// 进度条宽度
				currentPercent: 0, // 当前播放进度百分比
				currentPlaiedTime: 0, // 当前播放时间进度，单位：s
				songLyric: [] ,// 歌词
				scrollTopByLyric: 0, // 歌词滚动距离（等于行高）
				songLyricLineHeight: 80, // 每行歌词高度
				currentLineNo: 0 ,// 高亮当前行
				currentPos: 6 ,// 展示的行数
				imageMainColor: '',
				sysInfo: null
			}
		},
		onReady() {
			const sys = uni.getSystemInfoSync();
			// console.log(sys);
			this.sysInfo = sys;
			this.pageHeight = sys.windowHeight - sys.statusBarHeight;
		},
		onLoad(e) {
			this.id = e.id ? e.id : 0;
			
			uni.kHttp.get('/song/detail', {
				params: {
					ids: this.id
				}
			}).then(res => {
				// console.log(res);
				let data = res.data.songs[0];
				// console.log(data.al.picUrl);
				this.getImageMainColor(data.al.picUrl, 0);
				this.data = data;
				this.$nextTick(() => {
					const query = uni.createSelectorQuery().in(this);
					query.select('#slider-area').boundingClientRect(data => {
					  // console.log("得到布局位置信息" + JSON.stringify(data));
					  // console.log("节点离页面顶部的距离为" + data.top);
					  this.sliderMaxWidth = data.width;
					}).exec();
				})
			}).catch(err => {
				console.log(err);
			})
			
			this.getSongUrl(this.id);
			
			this.getSongLyric(this.id);
		},
		methods: {
			// 获取图片主色调
			getImageMainColor(src, index) {
				uni.kGetImgPrimaryColor(src, index, false, 300, this.pageHeight, 10).then(res => {
					// console.log(res, '图片主色');
					this.mainColor = `rgba(${res.r}, ${res.g}, ${res.b}, 0.5)`;
					this.imageMainColor = `rgba(${res.r}, ${res.g}, ${res.b}, 0.5)`;
					// let multiColorRes = this.multiplyColor([res.r, res.g, res.b], [0,188,121]);
					let multiColorRes = this.multiplyColor([res.r, res.g, res.b], [160,82,45]);
					// this.mainColor = `rgba(${multiColorRes[0]}, ${multiColorRes[1]}, ${multiColorRes[2]}, 0.5)`;
					this.mainColor = [multiColorRes[0], multiColorRes[1], multiColorRes[2]];
				}).catch(err => {
					console.log(err);
				})
				// console.log(color, 222);
				return src;
			},
			// 计算两个颜色叠加值
			multiplyColor(rgb1, rgb2) {
				var result = [],
					i = 0;
				for (; i < rgb1.length; i++) {
					result.push((Math.floor(rgb1[i] * rgb2[i] / 255)));
				}
				// console.log(result);
				return result;
			},
			getSongUrl(id) {
				uni.kHttp.get('/song/url', {
					params: {
						id: id
					}
				}).then(res => {
					// console.log(res);
					if (res.data.code == 200) {
						let data = res.data.data[0];
						this.songUrlData = data;
						// console.log(data);
						innerAudioContext = uni.createInnerAudioContext();
						innerAudioContext.autoplay = false;
						innerAudioContext.src = data.url;
						if (innerAudioContext.src) {
							setTimeout(() => {
								// console.log(innerAudioContext.duration);
								// console.log(Math.ceil(innerAudioContext.duration));
								let duration = Math.floor(innerAudioContext.duration);
								this.songEndTime = uni.kFormatSeconds(duration);
							}, 1000);
						}
					}
				}).catch(err => {
					console.log(err);
					// uni.showToast({
					// 	title: err.errMsg
					// });
				})
			},
			// 获取歌词
			getSongLyric(id) {
				uni.kHttp.get('/lyric', {
					params: {
						id: id
					}
				}).then(res => {
					// console.log(res);
					if (res.data.code == 200) {
						let data = res.data;
						// this.songLyric = data.lrc.lyric;
						let arr = data.lrc.lyric.split('\n');
						// console.log(arr);
						let lyricArr = [];
						for (let i in arr) {
							// 截取歌词时间
							lyricArr[i] = {
								lyric: arr[i],
								time: 0,
								seconds: 0,
								active: false
							}
							let timeMatch = arr[i].match(/\[(\S*)\]/);
							if (arr[i]) {
								lyricArr[i].time = timeMatch[1];
								// 转换为s
								// console.log(lyricArr[i].time.split(':'));
								let timeToArr = lyricArr[i].time.split(':');
								lyricArr[i].seconds = parseFloat(Number(timeToArr[0] * 60) + Number(timeToArr[1]));
								// console.log(lyricArr[i]);
								let index = arr[i].indexOf(']');
								lyricArr[i].lyric = arr[i].substr(index+1, arr[i].length);
							}
						}
						this.songLyric = lyricArr;
						this.songLyric[0].active = true;
						// console.log(this.songLyric);
					}
				}).catch(err => {
					console.log(err);
				})
			},
			// 高亮显示歌词当前行及文字滚动控制，行号为currentLineNo
			setLineHigh() {
				if (this.currentLineNo > 0) {
					this.songLyric[this.currentLineNo-1].active = false; // 取消上一行的歌词高亮激活状态
				}
				this.songLyric[this.currentLineNo].active = true; // 激活当前行的歌词高亮状态
				
				// 文字滚动
				this.scrollTopByLyric = this.currentLineNo * this.songLyricLineHeight / 2;
			},
			// 重置歌词显示状态
			resetSongLyricStatus() {
				this.currentLineNo = 0;
				this.scrollTopByLyric = 0;
			},
			switchTaped(e) {
				this.switchId = e.id;
				// console.log(this.switchId);
				for (let i in this.switchList) {
					this.switchList[i].active = !this.switchList[i].active;
				}
			},
			// 处理歌曲作者字符拼接
			handleSongArtlist(artLists) {
				let name = '';
				let nameList = [];
				if (!artLists.length) {
					return name;
				}
			
				artLists.map(item => {
					nameList.push(item.name);
				})
			
				name = nameList.join('/');
			
				return name;
			},
			back() {
				uni.navigateBack({
					delta: 1,
					animationType: 'slide-out-bottom'
				});
			},
			tapedBottomBar(index) {
				if (index == 2) {
					if (!this.playStatus && !this.songUrlData.url) {
						uni.showToast({
							title: '歌曲播放出错',
							icon: 'error'
						});
						return false;
					}
					this.tapedPlay();
				}
			},
			tapedPlay() {
				// console.log(222);
				this.bottomBarList[2].iconcode = this.playStatus ? '&#xea82;' : '&#xe6e4;'
				this.bottomBarList[2].title = this.playStatus ? '播放' : '暂停';
				this.playStatus ? innerAudioContext.pause() : innerAudioContext.play();
				// console.log(this.bottomBarList[2]);
				if (!this.playStatus) {
					setTimeout(() => {
						innerAudioContext.onTimeUpdate(() => {
							// console.log(innerAudioContext, '监听音频播放进度');
							this.currentPercent = (innerAudioContext.currentTime / innerAudioContext.duration) * 100;
							// console.log(uni.kFormatSeconds(innerAudioContext.currentTime));
							this.currentPlaiedTime = innerAudioContext.currentTime;
							// console.log('当前播放时间进度：' + this.currentPlaiedTime);
							if (this.currentLineNo == this.songLyric.length) {
								return false;
							}
							if (this.songLyric[this.currentLineNo].seconds <= this.currentPlaiedTime + 1) {
								this.setLineHigh(); // 高亮当前行
								this.currentLineNo++;
							}
							this.songCurrentTime = uni.kFormatSeconds(this.currentPlaiedTime);
							// 计算播放滑块移动距离
							this.countSliderActiveWidth(this.currentPercent);
							// uni.kDebounce(this.countSliderActiveWidth(this.currentPercent), 1000);
						})
						innerAudioContext.onEnded(() => {
							this.playStatus = false;
							this.bottomBarList[2].iconcode = '&#xea82;'
							this.resetSongLyricStatus();
						})
					}, 800);
				}
				this.playStatus = !this.playStatus;
			},
			/**
			 * @description 根据百分比计算播放进度
			 */
			countSliderActiveWidth(percent) {
				// console.log(Math.floor(percent));
				// 此处减5是减去中间滑块所占的宽度，5为大致数字，可自己根据实际情况调整
				this.sliderMoveX = (this.sliderMaxWidth - 5) * (Math.floor(percent) / 100);
				// console.log(this.sliderMoveX);
			},
			changeBySlider(e) {
				// console.log(e);
				// 判断是是否是手动拖动事件
				if (e.detail.source == 'touch') {
					this.sliderMoveX = e.detail.x;
					// console.log(this.sliderMoveX / this.sliderMaxWidth * 100);
					let percent = this.sliderMoveX / (this.sliderMaxWidth - 5);
					// 计算音频当前播放位置（单位：s）
					let currentTime = innerAudioContext.duration * percent;
					// console.log(currentTime);
					// 判断计算的时间是否大于音频总长度
					currentTime = currentTime > innerAudioContext.duration ? innerAudioContext.duration : currentTime;
					this.songCurrentTime = uni.kFormatSeconds(currentTime);
					// 同步音频当前播放位置
					innerAudioContext.currentTime = Math.floor(currentTime);
				}
			}
		}
	}
</script>

<style lang="scss">
	$content-width:650rpx;
	$slider-width: 18rpx;
	$slider-bg: rgba(255, 255, 255, 1);
	.page {
		overflow: hidden;
		// background-color: #007AFF;
	}
	.content-body {
		width: $content-width;
	}
	.song-pic {
		width: $content-width;
		height: $content-width;
	}
	// .slider-area {
	// 	bor
	// }
	.slider-active {
		height: 3px;
		border-top-left-radius: 3px;
		border-bottom-left-radius: 3px;
	}
	.slider-point {
		&::after {
			content: '';
			position: absolute;
			border-radius: $slider-width;
			width: $slider-width;
			height: $slider-width;
			background-color: $slider-bg;
			transform: translatex(-$slider-width*2);
			transform: translateY(-$slider-width/3);
		}
	}
</style>
